package com.urea.common.config;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.urea.common.core.domain.model.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 类描述:
 *
 * @author fangXu
 * @version 1.0
 * @date 2023/8/11 10:14
 */
@Component
@Slf4j
public class MybatisPlusAutoFillConfig implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("############自动填充新增参数#############");
        strictInsertFill(metaObject,"createdTime",LocalDateTime.class,LocalDateTime.now());
        strictInsertFill(metaObject,"updatedTime",LocalDateTime.class,LocalDateTime.now());
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (Objects.nonNull(authentication)){
            Object loginUser = authentication.getPrincipal();
            if (Objects.nonNull(loginUser)&&loginUser instanceof LoginUser) {
                JSONObject from = JSONObject.from(loginUser);
                JSONObject user = from.getJSONObject("user");
                String userId = "";
                if (Objects.nonNull(user)){
                    userId = user.getString("userId");
                }else{
                    user = from.getJSONObject("customerUser");
                    userId = user.getString("id");
                }
                strictInsertFill(metaObject,"createBy", String.class,userId);
                strictInsertFill(metaObject,"updateBy", String.class,userId);
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("############自动填充修改参数#############");
        strictUpdateFill(metaObject,"updatedTime",LocalDateTime.class,LocalDateTime.now());
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (Objects.nonNull(authentication)){
            Object loginUser = authentication.getPrincipal();
            if (Objects.nonNull(loginUser)&&!"anonymousUser".equals(String.valueOf(loginUser))) {
                JSONObject from = JSONObject.from(loginUser);
                JSONObject user = from.getJSONObject("user");
                String userId = "";
                if (Objects.nonNull(user)){
                    userId = user.getString("userId");
                }else{
                    user = from.getJSONObject("customerUser");
                    userId = user.getString("id");
                }
                strictInsertFill(metaObject,"updateBy", String.class,userId);
            }
        }
    }
}
